<!--
 * @Descripttion:
 * @Author: caijj
 * @Date: 2021-02-04 16:17:34
 * @LastEditors: caijj
 * @LastEditTime: 2021-02-04 16:26:12
-->
<template>
  <BasicLayout>
    <template #wrapper>
      <!-- 搜索组件 -->
      <com-search
        :config-type="configType"
        @submit="onSearchReport"
        @export="val => onExportReport('performance', val)"
      ><el-button icon="el-icon-circle-plus-outline" type="success" @click="addRole">添加角色</el-button>
      </com-search>
      <!-- 表格组件 -->
      <tree-table
        :loading="loading"
        :columns="columns"
        :data="tableData"
        :current-page="pagination.current"
        :page-size="pagination.size"
        :overflow-prop="['name','description']"
        height="420px"
        :total="pagination.total"
        border
        @handlePaginationChange="handlePaginationChange"
      >
        <template slot="employeeCount" slot-scope="scope">
          <el-link :underline="false" type="primary" @click="roleNum(scope.item.id)">{{ scope.item.employeeCount }}</el-link>
        </template>
        <template slot="state" slot-scope="scope">
          <el-switch
            v-model="scope.item.state"
            active-value="ENABLE"
            inactive-value="DISABLE"
            active-text="开启"
            inactive-text="禁用"
            @change="switchState(scope.item,scope.$index)"
          />
        </template>
        <template slot="operate" slot-scope="scope">
          <el-link style="margin-right:10px" :underline="false" type="primary" title="添加人员" @click="addPerson(scope.item)">添加人员</el-link> <!-- class="el-icon-circle-plus" -->
          <el-link style="margin-right:10px" :underline="false" type="primary" title="设置权限" @click="goParth(scope.item.id)">设置权限</el-link> <!-- class="el-icon-setting" -->
          <el-link style="margin-right:10px" :underline="false" type="primary" title="编辑" @click="addRole('编辑角色',scope.item)">编辑</el-link> <!--  class="el-icon-edit" -->
          <el-link :underline="false" type="danger" title="删除" @click="sureDel(scope.item.id)">删除</el-link> <!-- class="el-icon-delete"  -->
          <!-- <el-button slot="reference">删除</el-button> -->
        </template>
      </tree-table>
      <!-- 弹窗组件 展示角色人员 -->
      <com-dialog title="角色人员" :visible.sync="visible">
        <tree-table
          :loading="loading"
          :columns="colsmall"
          :data="tableDatas"
          :current-page="page.current"
          :total="page.total"
          :layout="'total, prev, pager, next'"
          @handlePaginationChange="onPaginationChange"
        />
      </com-dialog>
      <!-- 弹窗组件 编辑添加角色 -->
      <com-dialog :title="title" :visible.sync="visibleRole">
        <el-form ref="roleForm" size="mini" :model="roleFormData" label-width="100px">
          <el-form-item
            label="添加角色"
            prop="name"
            :rules="[
              { required: true, message: '添加角色不能为空'},
              { pattern:/^(?!.*,)/gi,message:'不包含英文“,”' }
            ]"
          >
            <el-input v-model="roleFormData.name" maxlength="50" placeholder="请填写角色名称" />
          </el-form-item>
          <el-form-item
            label="角色描述"
            prop="description"
          >
            <el-input v-model="roleFormData.description" type="textarea" show-word-limit maxlength="150" :autosize="{ minRows: 3, maxRows: 6 }" placeholder="请输入角色描述" />
          </el-form-item>
          <el-form-item class="dialog-footer">
            <el-button type="primary" @click="btnEvent('roleForm',true)">确认</el-button>
            <el-button @click="btnEvent('roleForm')">取消</el-button>
          </el-form-item>
        </el-form>
      </com-dialog>
      <!-- 添加人员 -->
      <template v-if="visibleStaff">
        <com-dialog title="添加人员" :visible.sync="visibleStaff">
          <personnel-options
            v-model="principals"
            :department="cascader.options"
            :placeholder="'请选择员工'"
            :employees="employees"
            :default-props="{
              children: 'children',
              label: 'name'
            }"
            @onDepartmentClick="fetchDepartmentUser"
          />
          <span slot="footer" class="dialog-footer">
            <el-button size="small" @click="closeAdd">取 消</el-button>
            <el-button size="small" type="primary" @click="personAdd">确 定</el-button>
          </span>
        </com-dialog>
      </template>
    </template>
  </BasicLayout>
</template>
<script>
import { del, add, userAdd, update, roleList, getRoleUserList } from '@/api/roleApi';
import { getDepartmentUser, getDepartmentTree } from '@/api/partRoleApi';
// import { getDepartmentTree, getDepartmentList, delDepartment } from '@/api/partRoleApi';
import TreeTable from '@/components/common/TablePagination';
import ComSearch from '@/components/common/Comsearch';
// import MultipleTree from '@/components/common/MultipleTree';
import PersonnelOptions from '@/components/business/PersonnelOptions';
import ComDialog from '../common/dialog';
import { Column, Columns, colsmall } from './staticConfig';
export default {
  components: {
    ComSearch,
    ComDialog,
    PersonnelOptions,
    TreeTable
  },
  props: {
    /* 级联选项 */

  },
  data() {
    return {
      principals: [],
      roleId: '', // 正在操作的角色ID
      cascader: {
        type: 'cascader',
        prop: 'father',
        props: {
          emitPath: false,
          checkStrictly: true,
          value: 'id',
          label: 'name',
          expandTrigger: 'click'
        },
        label: '员工',
        labelWidth: '40px',
        placeholder: '请选择员工',
        options: []
      },
      employees: [],
      roleFormData: {
        name: '',
        description: ''
      },
      title: '添加角色',
      visibleStaff: false,
      visible: false,
      visibleRole: false,
      configType: Column,
      columns: Columns,
      colsmall: colsmall,
      tableDatas: [],
      pagination: {
        'current': 1, // 当前页
        'size': 10,
        'total': 0
      },
      page: { // 人员数量分页
        'current': 1, // 当前页
        'size': 10,
        'total': 0
      },
      tableData: [],
      loading: false,
      exporting: false,
      roleEditId: undefined,
      formData: {
        name: ''
      }
    };
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {
    visibleRole: {
      handler(val) {
        !val && this.$refs['roleForm'].resetFields();
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getList();
    this.getDepartTree();
    this.fetchDepartmentUser('');
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  // 方法集合
  methods: {
    // 关闭添加人员弹窗
    closeAdd() {
      this.principals = [];
      this.visibleStaff = false;
    },
    // 弹窗翻页
    onPaginationChange({ current, size }) {

    },
    // 列表翻页
    handlePaginationChange({ current, size }) {
      this.pagination.size = size;
      this.pagination.current = current;
      this.getList();
    },
    // 确定添加人员
    personAdd() {
      // console.log(this.principals);
      const params = {
        id: this.roleId,
        idUserList: this.principals
      };
      userAdd(params).then(({ data }) => {
        this.msgSuccess('添加人员成功');
        this.visibleStaff = false;
        this.getList();
      });
    },
    // 跳到设置权限页
    goParth(id) {
      // todo
      this.$router.push({ path: `/set-auth/${id}` });
    },
    // 切换启用禁用
    switchState(item, index) {
      const params = {
        'id': item.id,
        'state': item.state
      };
      const text = item.state === 'ENABLE' ? '启用成功' : '禁用成功';
      update(params).then(() => {
        this.msgSuccess(text);
      }).catch(() => {
        this.tableData[index].state = item.state === 'ENABLE' ? 'DISABLE' : 'ENABLE';
      });
    },
    // 获取列表
    getList() {
      const params = {
        ...this.formData,
        ...this.pagination
      };
      roleList(params).then(({ data, total }) => {
        this.loading = false;
        this.tableData = data;
        this.pagination.total = total;
      }).catch(() => {
        this.loading = false;
      });
    },
    /* 获取部门列表 */
    getDepartTree() {
      getDepartmentTree().then(({ data = {}, resultCode } = {}) => {
        if (resultCode === '0000') {
          data.children.forEach(item => {
            this.cascader.options.push(item);
          });
        }
      });
    },
    // 获取部门员工
    fetchDepartmentUser(department) {
      getDepartmentUser({ department }).then(
        ({ data = {}, resultCode } = {}) => {
          if (resultCode === '0000') {
            this.employees = data.map(({ name, userId }) => ({
              name,
              userId
            }));
          }
        }
      );
    },
    // 添加人员 弹窗
    addPerson({ id: roleId, principals }) {
      this.visibleStaff = true;
      this.roleId = roleId;
      this.principals = principals || [];
    },
    /* 添加编辑角色保存 */
    btnEvent(ref, flag) {
      if (flag) {
        this.$refs[ref].validate(valid => {
          if (valid) {
            // 添加角色操作逻辑
            let text = '新增';
            let XMLHttp = add;
            const params = {
              ...this.roleFormData
            };
            if (this.title === '编辑角色') {
              XMLHttp = update;
              params.id = this.roleEditId;
              text = '编辑';
            }
            XMLHttp(params).then(() => {
              this.msgSuccess(`${text}成功`);
              this.visibleRole = false;
              this.getList();
            });
          }
        });
      } else {
        this.visibleRole = false;
      }
    },
    // 确定删除
    sureDel(id) {
      this.$confirm('确定删除该角色吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        del({ id, isDeleted: 1 }).then(() => {
          this.msgSuccess('删除成功');
          this.getList();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 添加角色
    addRole(title, item = {}) {
      this.title = title === '编辑角色' ? '编辑角色' : '添加角色';
      this.roleEditId = item.id;
      this.roleFormData.name = item.name;
      this.roleFormData.description = item.description;
      this.visibleRole = true;
    },
    // 查看角色人员
    roleNum(id) {
      this.visible = true;
      const params = {
        id,
        ...this.page
      };
      getRoleUserList(params).then(({ data, total }) => {
        this.tableDatas = data;
        this.page.total = total;
      });
    },
    onSearchReport(form) {
      this.loading = true;
      this.tableData = [];
      this.$nextTick(() => {
        this.formData = {
          ...this.formData,
          ...form
        };
        this.getList();
      });
    }
  }
};
</script>
<style lang='scss' scoped>
</style>
